<template>
  <div class="area-scheme">
    <el-dialog v-model="dialogVisible" :before-close="handleClose">
      <template #header>
        <div class="my-header">
          <div>{{ titleName }}</div>
        </div>
      </template>
      <div class="scheme-box">
        <div class="name-box">
          <span>方案名称：</span>
          <el-input v-model="schemeName" placeholder="请输入" />
          <span>模型类型：</span>
          <el-select
            v-model="modelTypeValue"
            class="m-2"
            placeholder="请选择"
            @change="handleChangeModel"
          >
            <el-option
              v-for="item in modelTypeList"
              :key="item.modelType"
              :label="item.typeName"
              :value="Number(item.modelType)"
            />
          </el-select>
        </div>

        <!-- @@ -->
        <div class="config-info">
          <div class="content-box">
            <div class="content-left">
              <div class="left-title">控制断面名称</div>
              <div class="left-box">
                <div
                  :class="['box-item', currentIndex == index ? 'active' : '']"
                  :key="index"
                  v-for="(item, index) in secList"
                >
                  <span @click="handleClickSec(item, index)">{{ item.blknm }}</span>
                </div>
              </div>
            </div>
            <div class="content-right">
              <div class="right-title">
                区域计算方案设置区-
                <span>{{ secCurrentObject?.blknm }}</span>
              </div>
              <div class="right-box">
                <model-param-select
                  ref="modelParamSelectRef"
                  :model-type="modelTypeValue"
                  :scheme-info="schemeInfo"
                  :sec-current-object="secCurrentObject"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSaveScheme">保存</el-button>
          <el-button @click="handleClose()">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, defineExpose } from 'vue'
import { storeToRefs } from 'pinia'
import ModelParamSelect from './cpns/modelParamSelect.vue'
import { useModelParams } from '@/store/modules/dispatch-manage.js'
const useModelParamsStore = useModelParams()
const { saveFormParams, modelSchemeList, modelSchemeDetail } = storeToRefs(useModelParamsStore)
import {
  // 断面列表
  getAreaSecList,
  // 模型类型列表
  getCalcModelType,
  //查看方案详情
  getAreaSchemeConfig,
  saveAreaSchemes,
  getPmSchemes
} from '@/services/modules/compute-methods'
const emit = defineEmits(['handleCloseDialog'])
// 方案名称
const schemeName = ref('')
// 弹框标头
const titleName = ref('')
// 控制弹框显隐
const dialogVisible = ref(false)
// 方案信息
const schemeInfo = ref({})
// 模型类型列表
const modelTypeList = ref([])
// 选择的模型类型的值
const modelTypeValue = ref('')
//控制断面列表
const secList = ref('')
// 选中断面的索引值
const currentIndex = ref('')
// 选中的断面信息
const secCurrentObject = ref({})

const modelParamSelectRef = ref(null)
function handleClose() {
  dialogVisible.value = false
}
//保存参数
const handleSaveScheme = () => {
  console.log(saveFormParams.value, '999')

  if (schemeInfo.value.row.id) {
    saveAreaSchemes({
      id: schemeInfo.value.row.id,
      zid: schemeInfo.value.zId,
      model: modelTypeValue.value,
      scName: schemeName.value,
      paramConf: saveFormParams.value
    }).then((res) => {
      if (res.code === 200) {
        handleClose()
        emit('handleClosePage')
        ElMessage.success(res.msg)
      }
    })
  } else {
    saveAreaSchemes({
      zid: schemeInfo.value.zId,
      model: modelTypeValue.value,
      scName: schemeName.value,
      paramConf: saveFormParams.value
    }).then((res) => {
      if (res.code === 200) {
        handleClose()
        emit('handleClosePage')
        ElMessage.success(res.msg)
      }
    })
  }
}
// 获取模型类型列表
const getCalcModelTypeList = () => {
  return new Promise((resolve, reject) => {
    getCalcModelType().then((res) => {
      if (res.code === 200) {
        modelTypeList.value = res.data
        resolve(modelTypeList.value)
      }
    })
  })
}
//获取区域断面 id 区域id
const getSecList = (id) => {
  return new Promise((resolve, reject) => {
    getAreaSecList({ zid: id }).then((res) => {
      if (res.code === 200) {
        secList.value = res.data
        resolve(secList.value)
      }
    })
  })
}
//获取所有断面参数信息
function getAreaSchemeConfigList(schemeId) {
  return new Promise((resolve, reject) => {
    getAreaSchemeConfig({ scid: schemeId }).then((res) => {
      if (res.code === 200) {
        modelSchemeDetail.value = res.data.paramConf
        saveFormParams.value = modelSchemeDetail.value.map((child) => {
          return {
            blkcd: child.blkcd,
            chlMid: child.chlMid,
            chlScid: child.chlScid
          }
        })
        resolve(modelSchemeDetail.value)
      }
    })
  })
}
function filterFirstByNamePerBlkcd(data) {
  let result = []
  // 使用 Set 来存储已经处理过的 blkcd 值，避免重复处理
  const processedBlkcd = new Set()

  // 遍历数据
  for (const item of data) {
    const currentBlkcd = item.blkcd

    // 检查是否已经处理过当前的 blkcd 值
    if (!processedBlkcd.has(currentBlkcd)) {
      // 将找到的item添加到结果数组中
      result.push({
        blkcd: item.blkcd,
        chlScid: item.id,
        chlMid: item.mid,
        pmid: item.pmid,
        chlScidName: item.name
      })
      // 将处理过的 blkcd 值添加到 Set 中
      processedBlkcd.add(currentBlkcd)
    }
  }

  // 返回结果数组
  return result
}
//获取所有断面方案
function getAllSecParams(chlMid) {
  //获取参数
  return new Promise((resolve, reject) => {
    saveFormParams.value = []
    getPmSchemes({ modelType: modelTypeValue.value, mid: chlMid, zid: schemeInfo.value.zId }).then(
      (res) => {
        if (res.code === 200 && res.data?.length) {
          modelSchemeList.value = res.data
          saveFormParams.value = filterFirstByNamePerBlkcd(modelSchemeList.value)
          resolve(modelSchemeList.value)
        }
      }
    )
  })
}
/**
 * 选中断面
 */
const handleClickSec = (item, index) => {
  // 选中断面的信息
  secCurrentObject.value = item
  currentIndex.value = index
}
// 打开弹框
const handleOpenModal = async (row) => {
  dialogVisible.value = true
  // 存储方案信息
  schemeInfo.value = row
  //  获取模型类型列表
  await getCalcModelTypeList()
  //  获取断面列表
  await getSecList(schemeInfo.value.zId)
  // 如果是修改
  if (row.row.id) {
    titleName.value = '修改方案'
    schemeName.value = row.row.scName
    modelTypeValue.value = row.row.model
    let arr = modelTypeList.value.filter((e) => {
      return e.modelType == row.row.model
    })
    await getAllSecParams(Number(arr[0].code))
    await getAreaSchemeConfigList(row.row.id)
    //  进入页面默认选中第一个断面
    handleClickSec(secList.value[0], 0)
  } else {
    titleName.value = '新建方案'
    schemeName.value = ''
    // 新建 则默认选中第一个模型类型
    modelTypeValue.value = modelTypeList.value[0].modelType
    await getAllSecParams(1)
    //  进入页面默认选中第一个断面
    handleClickSec(secList.value[0], 0)
  }
}
//修改模型类型
const handleChangeModel = (val) => {
  // if (val == -1) {
  //   val = undefined
  // }
  let arr = modelTypeList.value.filter((e) => {
    return e.modelType == val
  })
  getAllSecParams(Number(arr[0].code))
}
defineExpose({ handleOpenModal })
</script>

<style lang="less" scoped>
.area-scheme {
  .my-header {
    height: 35px;
    border-bottom: 2px solid #eee;
  }
  .name-box {
    display: flex;
    align-items: center;
    height: 30px;
    span {
      width: 150px;
    }
    :deep(.el-input) {
      width: 200px;
      margin-right: 20px;
    }
  }
  .config-info {
    width: 100%;
    height: 55vh;
    margin-top: 15px;
    .content-box {
      display: flex;
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      .content-left {
        width: 150px;
        height: 100%;
        border-right: 2px solid #eee;
        .left-title {
          height: 40px;
          background: #eee;
          display: flex;
          justify-content: center;
          align-items: center;
          color: black;
        }
        .left-box {
          height: calc(100% - 40px);
          overflow-y: auto;
          .box-item {
            height: 30px;
            color: gray;
            display: flex;
            justify-content: space-between;
            align-items: center;
            &.active {
              span:nth-of-type(1) {
                cursor: pointer;
                color: #409eff;
              }
            }
            &:hover {
              span:nth-of-type(1) {
                cursor: pointer;
                color: #409eff;
              }
            }
            span:nth-of-type(2) {
              color: #409eff;
              margin-right: 10px;
            }
          }
        }
      }
      .content-right {
        width: calc(100% - 150px);
        height: 100%;
        padding-left: 10px;
        .right-title {
          height: 30px;
          line-height: 30px;
        }
        .right-box {
          height: calc(100% - 30px);
        }
      }
    }
  }
}
</style>
